package com.co.vote.web.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.co.server.constant.Constant;
import com.co.server.entity.user.TUserLogin;
import com.co.server.entity.user.TUsers;
import com.co.server.service.user.TUserLoginService;
import com.co.server.service.user.TUsersService;
import com.co.server.service.user.impl.UsersSession;
import com.co.vote.constant.CookieConstant;
import com.co.vote.constant.SessionConstant;
import com.co.vote.utils.ClientUtil;
import com.co.vote.utils.CookieUtil;

public class RemembermeInterceptor extends HandlerInterceptorAdapter{
	
	@Resource
	private TUsersService tUsersService;
	@Resource
	private TUserLoginService tUserLoginService;

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		
		UsersSession userSession = (UsersSession)request.getSession().getAttribute(SessionConstant.SESSION_USER);

		if(!userSession.isLogin() && userSession.isRemembermeCheck()){
			//自动登录
			String userKey = CookieUtil.getCookieValue(request, CookieConstant.COOKIE_USER_KEY);
			if(StringUtils.isNotBlank(userKey)){
				//给用户自动登录
				TUserLogin userLogin = tUserLoginService.queryByRememberKey(userKey);
				if(userLogin != null){
					TUsers user = tUsersService.queryVoById(userLogin.getUserId());
					//用户存在且不为锁定状态
					if(user != null && user.getStatus() != Constant.STATUS_NOT_ACTIVE){
						tUsersService.updateLogin(userSession, user, ClientUtil.getIp(request));
					}
				}else{
					userSession.setRemembermeCheck(false);
				}
			}else{
				userSession.setRemembermeCheck(false);
			}
		}
		
		request.getSession().setAttribute(SessionConstant.SESSION_USER, userSession);
		return true;
	}

}
